package concurrent;

import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @author 26029
 * @date 2025/4/28
 * @description
 */
public class ForkJoinMergeSort {
    static class MergeSort extends RecursiveTask<int[]> {
        private final int[] arr;
        private final int start;
        private final int end;

        public MergeSort(int[] arr) {
            this(arr, 0, arr.length - 1);
        }

        private MergeSort(int[] arr, int start, int end) {
            this.arr = arr;
            this.start = start;
            this.end = end;
        }

        @Override
        protected int[] compute() {
            if (start >= end) {
                return new int[]{arr[start]};
            }

            int mid = start + (end - start) / 2;
            MergeSort leftTask = new MergeSort(arr, start, mid);
            MergeSort rightTask = new MergeSort(arr, mid + 1, end);

            leftTask.fork();
            rightTask.fork();
            int[] left = leftTask.join();
            int[] right = rightTask.join();

            int[] merged = new int[left.length + right.length];
            int l = 0, r = 0, pos = 0;
            while (l < left.length && r < right.length) {
                if (left[l] < right[r]) {
                    merged[pos++] = left[l++];
                } else {
                    merged[pos++] = right[r++];
                }
            }
            while (l < left.length) {
                merged[pos++] = left[l++];
            }
            while (r < right.length) {
                merged[pos++] = right[r++];
            }

            return merged;
        }
    }

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        MergeSort mergeSort = new MergeSort(new int[]{3, 6, 1, 4, 6, 82, 2});
        int[] result = pool.invoke(mergeSort);
        System.out.println(Arrays.toString(result));
    }
}
